﻿// ------------------------------------------------------------------------
//    YATSE - A touch screen remote controller for XBMC (.NET 3.5)
//    Copyright (C) 2010  Tolriq (http://code.google.com/p/yatse/)
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
// ------------------------------------------------------------------------

using System;
using System.IO;
using System.Windows;
using System.Windows.Threading;

namespace YATSE
{
    /// <summary>
    /// Logique d'interaction pour App.xaml
    /// </summary>
    public partial class App
    {

        protected override void OnStartup(StartupEventArgs e)
        {
            Current.DispatcherUnhandledException += AppDispatcherUnhandledException;
            base.OnStartup(e);
        }

        static void AppDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            var exception = e.Exception;
            var trace = new System.Diagnostics.StackTrace(exception, true);

            var errormessage = "Error [ " + exception.Message + " ]";
            errormessage += "\r\n" + trace.GetFrame(0).GetMethod().Name + " : " + trace.GetFrame(0).GetFileLineNumber() + " / " + trace.GetFrame(0).GetFileColumnNumber();
            errormessage += "\r\n" + exception.StackTrace;
            var inner = exception.InnerException;
            if (inner != null)
                errormessage += "\r\n -- Inner ---\r\n" + inner.StackTrace;
            WriteToLog(errormessage);
            e.Handled = true;
        }

        public static void WriteToLog(string message)
        {
            var logFile = System.Windows.Forms.Application.StartupPath + @"\Log\Yatse.log";
            var sw = new StreamWriter(logFile, true);
            sw.WriteLine(DateTime.Now + " : " + message);
            sw.Flush();
            sw.Close();
        }
    }
}
